package com.attendance.controller.api;

import com.alibaba.fastjson2.JSON;
import com.apifan.common.random.source.PersonInfoSource;
import com.attendance.entity.User;
import com.attendance.service.UserService;
import com.attendance.utils.GenerateEmailContent;
import com.attendance.utils.GenerateVerificationCode;
import com.attendance.utils.ResponseInfo;
import jakarta.annotation.Resource;
import jakarta.mail.internet.AddressException;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Resource
    public UserService userService;

    @Resource
    public GenerateEmailContent generateEmailContent;

    @Resource
    public GenerateVerificationCode generateVerificationCode;


    @PostMapping("/add") // 添加用户
    public String add(@Param("code") String code,
                      @Param("verify_code") String verify_code,
                      @Param("validity") String validity,
                      @Param("email") String email,
                      @Param("password") String password) {
        // 查询是否已注册
        User user = userService.selectOneByEmail(email);
        if (user != null) {
            return JSON.toJSONString(ResponseInfo.fail("用户已注册 ❓"));
        } else {
            user = new User();
        }

        HashMap<Object, Object> map = new HashMap<>();

        if (verify_code == null || verify_code.equals("")) {
            return JSON.toJSONString(ResponseInfo.fail("还没发验证码呢 🤡", 500));
        }


        Boolean result = generateVerificationCode.verifyCode(code, verify_code, Long.parseLong(validity));
        if (result) {
            user.setUsername(PersonInfoSource.getInstance().randomChineseName());
            user.setPassword(password);
            user.setEmail(email);
            userService.saveUserDetails(user);
            map.put("result", true);
            return JSON.toJSONString(ResponseInfo.success(map, "注册成功 ✅"));
        } else {
            if ((System.currentTimeMillis() - Long.parseLong(validity)) > 900000) {
                return JSON.toJSONString(ResponseInfo.fail("验证码过期 🕒", 500));
            }
            return JSON.toJSONString(ResponseInfo.fail("验证码错误 ❌", 500));
        }
    }

    @GetMapping("/code") // 发送验证码
    public String code(@Param("email") String email) throws UnsupportedEncodingException, AddressException {
//        System.out.println(email);
        // 生成验证码
        String code = generateVerificationCode.build("NUMBER", 6);
        // 生成加密验证码
        String encode = generateVerificationCode.encode(code);
        // 查询是否已注册
        User user = userService.selectOneByEmail(email);
        // 创建响应数据结构
        HashMap<Object, Object> map = new HashMap<>();

        // 业务判断
        if (user == null) {
            // 发送验证码
            Boolean result = generateEmailContent.SendRegisterVerifyCodeEmail(code, email);
            if (result) {
                map.put("verify_code", encode); // 验证码
                map.put("validity", System.currentTimeMillis()); // 有效期开始时间，有效期为15分钟。
                map.put("registered", false); // 是否注册
                map.put("result", true); // 结果
                return JSON.toJSONString(ResponseInfo.success(map, "发送成功 ✅"));
            } else {
                return JSON.toJSONString(ResponseInfo.fail("发送失败 ❌", 500));
            }
        } else {
            map.put("verify_code", null);
            map.put("validity", null);
            map.put("registered", true);
            map.put("result", true);
            return JSON.toJSONString(ResponseInfo.fail("用户已注册 ❓"));
        }
    }

    @GetMapping("/authentication") // 验证是否登录
    public String isAuthentication() {
        HashMap<Object, Object> map = new HashMap<>();
        map.put("isAuthentication", true);
        return JSON.toJSONString(ResponseInfo.success(map, "认证成功 ✅"));
    }

    @PostMapping("/rename")
    public String rename(@Param("email") String email, @Param("newName") String newName) {
        HashMap<Object, Object> map = new HashMap<>();
        int i = userService.renameByEmail(email, newName);
        if (i > 0) {
            return JSON.toJSONString(ResponseInfo.success(map, "修改成功 ✅"));
        } else {
            return JSON.toJSONString(ResponseInfo.fail("修改失败 ❌", 500));
        }
    }

    @GetMapping("/session")
    public String sessionInvalid() {
//        System.out.println("未授权请重新登录");
        return JSON.toJSONString(ResponseInfo.fail("未授权请重新登录 ❌", -1));
    }

}
